import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/res/app_configs.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/widgets/app_webview.dart';
import 'package:xws/widgets/photo_viewer.dart';
import 'package:xws/widgets/video_viewer.dart';

import 'app_util.dart';
import 'log_util.dart';
import 'storage_util.dart';
import 'theme_util.dart';

export 'package:permission_handler/permission_handler.dart';

/// 工具缓存
class _TU {
  _TU._();

  static DateTime? exitTime;
}

/// 初始化工具相关
Future<void> initTools() async {
  final SystemUiOverlayStyle s = SystemUiOverlayStyle.dark.copyWith(
    statusBarColor: Colors.transparent,
    systemNavigationBarDividerColor: Colors.transparent,
    systemNavigationBarColor: themeColor,
  );

  SystemChrome.setSystemUIOverlayStyle(s);

  WidgetsFlutterBinding.ensureInitialized();

  await initHive();
  await _initWeChat();
}

/// 初始化微信相关
Future<void> _initWeChat() async {
  try {
    registerWxApi(
      appId: AppConfigs.wechatAppId,
      universalLink: AppConfigs.wechatUniversalLink,
    );
  } catch (e) {
    error('初始化微信相关出错:$e');
  }
}

/// 取消焦点
/// * `checkFocus`为`true`时，没有焦点则不执行
void unFocus(BuildContext context, {bool checkFocus = true}) {
  try {
    if (checkFocus && !FocusScope.of(context).hasFocus) return;
    FocusScope.of(context).unfocus();
  } catch (e) {
    error('取消焦点出错:$e');
  }
}

/// 隐藏键盘
void hideKeyboard() {
  try {
    if (MediaQueryData.fromWindow(window).viewInsets.bottom > 0) SystemChannels.textInput.invokeMethod<void>('TextInput.hide');
  } catch (e) {
    error('隐藏键盘出错:$e');
  }
}

/// 选择图片
Future<List<String>?> pickImgs(
  BuildContext context, {
  int max = 1,
  bool withCamera = true,
}) async {
  bool _isLoading = false;

  try {
    final List<AssetEntity>? assets = await AssetPicker.pickAssets(
      context,
      maxAssets: max,
      specialItemPosition: SpecialItemPosition.prepend,
      specialItemBuilder: (BuildContext context) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () async {
            final AssetEntity? entity = await CameraPicker.pickFromCamera(context, enableRecording: false);

            if (entity == null) return;

            final AssetPicker<AssetEntity, AssetPathEntity> picker = context.findAncestorWidgetOfExactType()!;
            final DefaultAssetPickerProvider p = picker.builder.provider as DefaultAssetPickerProvider;
            await p.currentPathEntity!.refreshPathProperties();
            await p.switchPath(p.currentPathEntity!);
            p.selectAsset(entity);
          },
          child: const Center(
            child: Icon(Icons.camera_enhance, size: 42.0),
          ),
        );
      },
      pickerTheme: AssetPicker.themeData(theme(context)).copyWith(),
    );

    if (assets != null && assets.isNotEmpty) {
      final List<String> files = <String>[];
      loading(context);
      _isLoading = true;
      delayed(const Duration(milliseconds: 300));

      for (final AssetEntity a in assets) {
        final File? f = await a.file;
        if (f != null) {
          final File cf = await _compressAndGetFile(context, f);
          files.add(cf.path);
        }
      }

      close(context);
      _isLoading = false;

      return files;
    }
  } catch (e) {
    if (_isLoading) close(context);

    error('选择图片出错:$e');
  }
}

/// 拍摄视频
Future<String?> pickVideo(
  BuildContext context, {
  Duration maxDuration = const Duration(seconds: 10),
}) async {
  try {
    // final bool? useCamera = await showOptions(
    //   context,
    //   const PickVideo(),
    //   title: '选择方式',
    //   backgroundColor: white(context),
    // );
    // if (useCamera == null) return null;

    // if (useCamera) {
    final AssetEntity? entity = await CameraPicker.pickFromCamera(
      context,
      enableRecording: true,
      onlyEnableRecording: true,
      maximumRecordingDuration: maxDuration,
    );
    if (entity != null) {
      final File? f = await entity.file;
      return f?.path;
    }
    // } else {
    //   final List<AssetEntity>? assets = await AssetPicker.pickAssets(
    //     context,
    //     maxAssets: 1,
    //     pickerTheme: AssetPicker.themeData(theme(context)).copyWith(),
    //     requestType: RequestType.video,
    //   );

    //   if (assets != null && assets.isNotEmpty && (await assets.single.file) != null) {
    //     return (await assets.single.file)?.path;
    //   }
    // }
  } catch (e) {
    error('拍摄视频出错:$e');
  }
}

/// 预览资源
Future<void> assetsViewer(
  BuildContext context,
  List<String> assets, {
  bool isVideo = false,
  int initIndex = 0,
  String heroTag = 'image',
}) async {
  try {
    if (isVideo) {
      await push(context, VideoViewer(videos: assets, initIndex: initIndex), routeType: RouteType.fade);
    } else {
      await push(
          context,
          PhotoViewer(
            images: assets,
            initIndex: initIndex,
            heroTag: heroTag,
          ),
          routeType: RouteType.fade);
    }
  } catch (e) {
    error('预览视频出错:$e');
  }
}

///压缩文件并返回压缩后的文件
/// * `file` 文件对象
/// * `targetPath` 输出路径
Future<File> _compressAndGetFile(BuildContext context, File file, {String? targetPath}) async {
  try {
    double _quality = 0.8;
    final int _fileSize = file.lengthSync() ~/ 1024;
    if (_fileSize > 2048) {
      _quality = 2048 / _fileSize;
    }

    final String _fileName = file.path.split('/').last;

    final String _targetPath = targetPath ?? await getLocalPath('temp') + 'image_${DateTime.now().millisecondsSinceEpoch}.' + _fileName.split('.')[1];

    final Uint8List? result = await FlutterImageCompress.compressWithFile(
      file.absolute.path,
      quality: (100 * _quality).ceil(),
    );

    if (result == null) return file;

    final File _f = File(_targetPath);
    await _f.create();
    _f.writeAsBytesSync(result);

    return _f;
  } catch (e) {
    error('压缩文件失败:$e');
    return file;
  }
}

/// 延时
Future<void> delayed(Duration duration) async => await Future<void>.delayed(duration, () {});

/// 打开h5
Future<T?> openH5<T extends Object>(
  String url, {
  BuildContext? context,
  String pic = '',
  bool clearCache = true,
}) async =>
    await push<T>(
      context ?? appNavigatorKey.currentContext!,
      AppWebView(url: url, pic: pic, clearCache: clearCache),
    );

/// 获取权限
Future<bool> getPermission(Permission per, {bool openSettings = true}) async {
  try {
    final PermissionStatus _p = await per.request();

    info('$per status $_p');

    if (_p.isGranted || _p.isLimited) {
      return true;
    } else {
      if (openSettings) {
        bool success = false;

        delayed(const Duration(milliseconds: 500)).then((_) async {
          final bool s = await openAppSettings();
          if (s) success = (await per.isGranted) || (await per.isLimited);
        });

        return success;
      }
    }

    if (_p.isPermanentlyDenied && openSettings) {
      final bool re = await openAppSettings();
      debug('openAppSettings:$re');

      final PermissionStatus _p2 = await per.request();
      return _p2.isGranted;
    }

    return false;
  } catch (e) {
    error('权限获取出错:$e');
    return false;
  }
}

/// 分享物品(分享小程序)
Future<void> shareGoods(GoodsObj obj) async {
  try {
    StreamSubscription<BaseWeChatResponse>? _listen;

    _listen = weChatResponseEventHandler.listen((BaseWeChatResponse bcr) {
      if (bcr.isSuccessful) shareAGoods(obj.id);
      _listen?.cancel();
    });

    final bool r = await shareToWeChat(
      WeChatShareMiniProgramModel(
        webPageUrl: '/',
        path: 'pages/goods_detail/goods_detail?id=' + obj.id,
        title: obj.name,
        description: obj.description,
        miniProgramType: WXMiniProgramType.RELEASE,
        thumbnail: WeChatImage.network(obj.photoUrlList.first),
        userName: AppConfigs.wechatMiniProgramUserName,
      ),
    );

    if (!r) et('请安装微信');
  } catch (e) {
    error('分享物品出错:$e');
  }
}

/// 按两次退出拦截
Future<bool> exitHold(BuildContext context) async {
  if (_TU.exitTime == null) {
    ///重置时间，弹出提示
    _TU.exitTime = DateTime.now();
    ct('再按一次退出');
    return Future<bool>.value(false);
  } else {
    if (DateTime.now().difference(_TU.exitTime!).inSeconds > 2) {
      ///重置时间，弹出提示
      _TU.exitTime = DateTime.now();
      ct('再按一次退出');
      return Future<bool>.value(false);
    }
  }

  pop(context, ex: true);

  return Future<bool>.value(true);
}
